package cn.omisheep.au.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zhou xin chen  😊
 * 联系方式 qq:1269670415  email:xinchenzhou666@gmail.com
 */
@Slf4j
public class AuUtil {


    private static final Pattern JSON_RSA_PATTERN = Pattern.compile("\\{.*\".*\".*:.*\"(.*)\".*}");

    public static String parse_RSA_JSON(String json) {
        Matcher matcher = JSON_RSA_PATTERN.matcher(json);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return "";
    }

    public static long parseTimeValue(String time) {
        if (time == null) {
            return 0L;
        } else {
            String normalized = time.toLowerCase(Locale.ROOT).trim();
            if (normalized.endsWith("d")) {
                return 1000 * TimeUnit.DAYS.toSeconds(parse(normalized, "d"));
            } else if (normalized.endsWith("h")) {
                return 1000 * TimeUnit.HOURS.toSeconds(parse(normalized, "h"));
            } else if (normalized.endsWith("m")) {
                return 1000 * TimeUnit.MINUTES.toSeconds(parse(normalized, "m"));
            } else {
                return 1000 * TimeUnit.SECONDS.toSeconds(parse(normalized, "s"));
            }
        }
    }

    private static long parse(String normalized, String suffix) {
        String s = normalized.substring(0, normalized.length() - suffix.length()).trim();
        try {
            long value = Long.parseLong(s);
            if (value >= 0L) {
                return value;
            }
        } catch (Exception e) {
            return 0;
        }
        return 0;
    }

    public static String beautifulJson(Object o) {
        try {
            return new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(o);
        } catch (JsonProcessingException e) {
            log.error("JsonProcessingException => {}", e.getMessage());
            return "";
        }
    }


}
